<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="id">
        <el-input v-model="queryParams.id" placeholder="团队ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="" prop="groupName">
        <el-input v-model="queryParams.groupName" placeholder="团队名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="" prop="regimental">
        <el-input v-model="queryParams.regimental" placeholder="团长姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="" prop="email">
        <el-input v-model="queryParams.email" placeholder="邮箱" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="审核状态" clearable>
          <el-option v-for="item, index in auditStatusOptions" :key="index" :label="item" :value="index" />
        </el-select>
      </el-form-item>

      <el-form-item label="" prop="dateRange">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleBatchApprove" :disabled="!isChecked">批量通过</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" size="mini" @click="handleBatchReject" :disabled="!isChecked">批量拒绝</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="teamList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="handleDisabled" />
      <el-table-column prop="id" label="团队ID"></el-table-column>
      <el-table-column prop="groupName" label="团队名称"></el-table-column>
      <el-table-column prop="regimental" label="团长姓名"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column label="审核状态">
        <template slot-scope="scope">
          <span :style="getAuditStatusStyle(scope.row.status)">
            {{ getAuditStatusText(scope.row.status) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="申请时间"></el-table-column>
      <el-table-column label="操作">

        <template slot-scope="scope">
          <el-button v-if="scope.row.status === '0'" type="text" @click="handleApprove(scope.row)">
            通过
          </el-button>
          <el-button v-if="scope.row.status === '0'" type="text" @click="showRejectDialog(scope.row)">
            拒绝
          </el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog title="审核原因" :visible="dialogVisible" @close="dialogVisible = false">
      <el-form ref="auditForm" label-position="left" label-width="80px">
        <el-form-item label="审核原因: ">
          <el-input v-model="rejectReason" placeholder="请输入审核原因"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <div class="buttons-container">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleReject">确认</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<style>
.input-container {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.input-prefix {
  margin-right: 20px;
}

.buttons-container {
  display: flex;
  justify-content: center;
}
</style>

<script>
import {
  listTeam,
  getTeam,
  delTeam,
  addTeam,
  updateTeam,
} from "@/api/team/sign";

export default {
  name: "Team",
  data() {
    return {
      // 遮罩层
      loading: true,
      selection: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      dateRange: "",
      // 非多个禁用
      multiple: true,
      isChecked: false,
      // 显示搜索条件
      showSearch: true,
      dialogVisible: false,
      rejectReason: "",
      selectedRow: null, // 保存选中行的数据
      // 总条数
      total: 0,
      // 申请加入表格数据
      teamList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      auditStatusOptions: ["待审核", "已通过", "未通过"],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: null,
        regimental: null,
        userId: null,
        email: null,
        phone: null,
        discount: null,
        currency: null,
        status: null,
        remark: null,
      },
      isSearch: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleDisabled(e) {
        return true;
    },
    /** 查询申请加入列表 */
    getList() {
      let params = {};
      if (this.isSearch) {
        params = this.addDateRange(this.queryParams, this.dateRange);
      } else {
        params = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        }
      }
      this.loading = true;
      listTeam(params).then(
        (response) => {
          this.teamList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    getAuditStatusText(status) {
      if (status === "0") {
        return "待审核";
      } else if (status === "1") {
        return "已通过";
      } else if (status === "2") {
        return "未通过";
      } else {
        return "";
      }
    },
    getAuditStatusStyle(status) {
      if (status === "0") {
        return {
          textAlign: "center",
          fontSize: "14px",
          color: "rgb(255, 149, 2)",
          fontWeight: "bold",
          alignItems: "center", // 注意：alignItems 属性适用于 flex 容器
        };
      } else if (status === "1") {
        return {
          textAlign: "center",
          fontSize: "14px",
          color: "rgb(24, 144, 255)",
          fontWeight: "bold",
          alignItems: "center", // 注意：alignItems 属性适用于 flex 容器
        };
      } else if (status === "2") {
        return {
          textAlign: "center",
          fontSize: "14px",
          color: "rgb(255, 58, 48)",
          fontWeight: "bold",
          alignItems: "center", // 注意：alignItems 属性适用于 flex 容器
        };
      } else {
        return {
          textAlign: "center",
          fontSize: "14px",
          color: "inherit",
          fontWeight: "normal",
          alignItems: "center", // 注意：alignItems 属性适用于 flex 容器
        };
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        teamId: null,
        userId: null,
        status: null,
        applyFor: null,
        verify: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.isSearch = true;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      this.isSearch = false;
      this.getList();

    },
    //多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
      this.selection = selection;
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      if (
        this.ids.length &&
        selection.some((item) => item.status === "0")
      ) {
        this.isChecked = true;
      } else {
        this.isChecked = false;
      }
    },
    async handleBatchApprove() {
      let selectedItems = [];
      this.selection.forEach(item => {
        if (item.status == '0') {
          selectedItems.push({
            ...item,
            status: "1",
          })
        }
      });
      const confirmText = `确定要通过选中的数据吗？`;
      this.$confirm(confirmText, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(async () => {
          try {
            for (let ite of selectedItems) {
              await updateTeam(ite);
            }
            this.$modal.msgSuccess("操作成功");
          } catch (error) {
            console.log(error);
          } finally {
            this.getList();
          }
        })
        .catch(() => {
          // 取消操作
        });
    },



    handleBatchReject() {
      this.showRejectDialog();
    },



    handleApprove(row) {
      this.$confirm("确定通过审核？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          row.status = "1";
          updateTeam(row).then((res) => {
            this.$modal.msgSuccess(res.msg);
            this.getList();
          });
        })
        .catch(() => {
          // 取消操作
        });
    },
    showRejectDialog(row) {
      this.selectedRow = row; // 保存选中行的数据
      this.dialogVisible = true; // 显示对话框
      this.rejectReason = "";
    },
    async handleReject() {
      if (this.rejectReason.trim() === "") {
        // 拒绝原因不能为空
        this.$message.error("请输入审核原因");
        return;
      }
      var row = this.selectedRow;
      if (!row) {
        const selectedItems = []
        this.selection.forEach(item => {
          if (item.status == '0') {
            selectedItems.push({
              ...item,
              verify: this.rejectReason,
              status: "2",
            })
          }
        });
        row = selectedItems;
      } else {
        row.verify = this.rejectReason;
        row.status = "2";
      }
      row = Array.isArray(row) ? row : [row];
      try {
        for (let ite of row) {
          await updateTeam(ite);
        }
        this.dialogVisible = false;
        this.$modal.msgSuccess("操作成功");
      } catch (error) {
        console.log(error);
      } finally {
        this.getList();
      }
    },

    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.ids = this.ids;
      this.download(
        "team/sign/export",
        {
          ...this.queryParams,
          ids: this.ids.length ? this.ids : undefined
        },
        `团队签约审核_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
